<?php

namespace App\Http\Controllers\Account;

use App\Models\Company;
use App\Models\Notification;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

/**
 * Date: 2018/1/26
 * @author George
 * @package App\Http\Controllers\Account
 */
class AccountController extends Controller
{
    /**
     * 获取用户信息
     *
     * Date: 2018/1/26
     * @author George
     * @return \Illuminate\Http\JsonResponse
     */
    public function profile()
    {
        $user = Auth::user();

        $company = Company::first();
        $user->company = $company->name;
        if ($user->admin) {
            $user->menus;
        }

        return response()->json($user);
    }

    /**
     * 更新用户信息
     *
     * Date: 2018/1/26
     * @author George
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function update(Request $request)
    {
        //验证表单内容
        $attributes = $this->validate($request, [
            'name' => 'required',
            'staffid' => 'required',
            'gender' => 'required',
            'email' => 'required',
            'password' => 'required',
            'avatar' => 'required'
        ]);
        //修改用户信息
        $user = $this->modifyAttributes($attributes);

        return response()->json($user);
    }

    /**
     * Date: 2018/1/26
     * @author George
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function modifyPassword(Request $request)
    {
		$this->validate($request, [
			'old_password' => 'required',
			'new_password' => 'required',
		], [
			'old_password.required' => '请输入旧密码',
			'new_password.required' => '请输入新密码',
		]);

		$oldPassword = $request->get('old_password');
		$newPassword = $request->get('new_password');

		$verifyResult = $this->verifyPassword($request->user(), $oldPassword);

		if ($verifyResult) {
			//更新用户密码
			$user = $this->modifyAttributes(['password' => $newPassword]);
		} else {
			return $this->failed('旧密码错误');
		}

        return response()->json($user);
    }

	/**
	 * 验证用户密码
	 *
	 * Date: 21/03/2018
	 * @author George
	 * @param User $user
	 * @param $plain
	 * @return bool
	 */
	private function verifyPassword(User $user, $plain)
	{
		return Hash::check($plain, $user->getAuthPassword());
	}

    /**
     * 更新用户属性
     *
     * Date: 2018/1/26
     * @author George
     * @param array $attributes
     * @return User
     * @throws \Throwable
     */
    protected function modifyAttributes(array $attributes): User
    {
        $user = Auth::user();

        //遍历属性数组更新用户属性
        foreach ($attributes as $key => $value) {
            $user->{$key} = $value;
        }

        //保存用户信息
        $user->saveOrFail();

        return $user;
    }

    public function menus()
    {
        $user = Auth::user();
        return $user->menus;
    }

	/**
	 * 获取用户通知
	 *
	 * Date: 2018/3/1
	 * @author George
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 */
	public function get_notification(Request $request)
	{
		$user = Auth::user();
		$notification = Notification::query();

		// 查询针对用户的通知
		$notifications = $notification->where('notifiable_id', $user->id)->orWhereNull('notifiable_id')->orderBy('created_at', 'desc')->get();

		// 查询用户已读通知
		$user_notification_pivots = DB::table('user_notification_pivot')
			->where('user_notification_pivot.user_id', $user->id)->get();

		// 删除已读通知
		if (count($user_notification_pivots)) {
			foreach ($notifications as $k => $v) {
				foreach ($user_notification_pivots as $k1 => $v1) {
					// 已读的加上已读时间
					if ($v1->read_at != null && $v->id == $v1->notification_id) {
						$v->read_at = $v1->read_at;
					}
					// 删除的就删除这条通知
					if ($v1->deleted_at != null && $v->id == $v1->notification_id) {
						unset($notifications[$k]);
					}
				}
			}
		}

		// 序列化通知内容
		$notifications->map(function ($item) {
			$item->data = json_decode($item->data);
			return $item;
		});

		return $this->success($notifications);
	}

	/**
	 * 用户通知标为已读
	 *
	 * Date: 2018/3/1
	 * @author George
	 * @param Notification $notification
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function notification_read(Notification $notification){

        $user = Auth::getUser();

        DB::table('user_notification_pivot')->insert([
            'user_id' => $user->id,
            'notification_id' => $notification->id,
            'read_at' => date('Y-m-d H:i:s'),
        ]);

        return $this->success(['设置成功']);
    }

	/**
	 * 用户通知标为删除
	 * Date: 2018/3/1
	 * @author George
	 * @param Notification $notification
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function notification_deleted(Notification $notification){

        $user = Auth::getUser();

        $user_notification_pivots = DB::table('user_notification_pivot')
            ->where('user_notification_pivot.user_id',$user->id)
            ->where('user_notification_pivot.notification_id',$notification->id)
            ->get();

        // 有记录就修改。没有记录就添加
        if(count($user_notification_pivots)){
            DB::table('user_notification_pivot')
                ->where('user_notification_pivot.user_id',$user->id)
                ->where('user_notification_pivot.notification_id',$notification->id)
                ->update([
                    'deleted_at' => date('Y-m-d H:i:s')
                ]);
        }else{
            DB::table('user_notification_pivot')->insert([
                'user_id' => $user->id,
                'notification_id' => $notification->id,
                'deleted_at' => date('Y-m-d H:i:s'),
            ]);
        }

        return $this->success(['删除成功']);
    }
}
